import React from 'react';
import { Form, Card, Input, Radio, Button, DatePicker, Row, Modal, Divider } from 'antd';
import { utils } from 'vv-frontend-components';
import TextArea from 'antd/es/input/TextArea';
import moment from 'moment';
import { history, connect } from 'umi';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { SelectForm } from '@/components/UserForm';
import { getTypeList } from '@/services/setting/recruitManage';
import { withRoutePage } from '@/utils/enhanceUtils';
import pageTabUtil from '@/utils/pageTabUtil';

import styles from './RecruitManage.less';

const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 }
};
const { deepTrim } = utils;
class RecruitEdit extends React.PureComponent {
    state = {
        visible: false,
        modalDelete: false // 控制模态框状态是否是删除
        // showDeleteBtn: false,
        // activeKey: '1'
    };

    componentDidMount() {
        const { dispatch, location } = this.props;
        const {
            query: { id = '', recruitmentCode = '', action = 'create' }
        } = location;

        if (action && action === 'edit') {
            dispatch({
                type: 'recruitManage/fetchPostDetail',
                payload: {
                    id,
                    code: recruitmentCode
                }
            });
        }
        // if (
        //     getPath(this.props, 'location.query.recruitId') &&
        //     getPath(this.props, 'location.query.recruitId') !== 'undefined'
        // ) {
        //     //页面删除职位功能
        //     this.setState({
        //         showDeleteBtn: true
        //     });
        // }
    }

    // 卸载清空数据
    componentWillUnmount() {
        const { dispatch } = this.props;
        dispatch({
            type: 'recruitManage/save',
            payload: { postDetail: {} }
        });
    }

    handleSubmit = ({ newUser }) => {
        const { form, dispatch, location, recruitManage } = this.props;
        const {
            postDetail: { id = '' }
        } = recruitManage;
        const {
            query: { action = 'create' }
        } = location;
        form.validateFields((err, values) => {
            if (!err) {
                if (action && action === 'edit') {
                    dispatch(
                        deepTrim({
                            type: 'recruitManage/editPost',
                            payload: {
                                ...values,
                                id,
                                createUser: newUser,
                                releaseTime: values.releaseTime.format('YYYY-MM-DD HH:mm:ss')
                            }
                        })
                    );
                } else {
                    dispatch(
                        deepTrim({
                            type: 'recruitManage/addPost',
                            payload: {
                                ...values,
                                createUser: newUser,
                                releaseTime: values.releaseTime.format('YYYY-MM-DD HH:mm:ss')
                            }
                        })
                    );
                }
            }
        });
    };

    showModal = type => {
        this.setState(
            {
                modalDelete: type
            },
            () => {
                this.setState({
                    visible: true
                });
            }
        );
    };

    handleOk = () => {
        this.setState({
            visible: false
        });
    };

    handleCancel = () => {
        const { modalDelete } = this.state;
        console.log(modalDelete);
        this.setState({
            visible: false
        });
        pageTabUtil.goBack();
        // history.push('/office/info/webSite/recruitList');
    };

    render() {
        const { form, recruitManage } = this.props;
        const { visible, modalDelete } = this.state;
        const { getFieldDecorator } = form;
        // 获取登陆人公司id
        const user = localStorage.getItem('user');
        const { employeeName: newUser } = user ? JSON.parse(user) : {};
        const { areaCode } = user ? JSON.parse(user) : {};
        const { postDetail = {} } = recruitManage;
        const {
            postCnName = '',
            postCnType = '',
            releaseTime = undefined,
            workPlace = undefined,
            workNature = undefined,
            postCnResponsibilit = '',
            jobCnRequirements = '',
            hidden = undefined
        } = postDetail;
        // 按照登录人的公司修改默认公司位置
        let userPlace = 1;
        if (areaCode === '86') {
            userPlace = 0;
        }
        // const formItemLayout = {
        //     labelCol: { span: 4 },
        //     wrapperCol: { span: 14 }
        // };
        return (
            <PageHeaderWrapper>
                <Card title="官网职位表单" bordered={false} className={styles.bodynopading}>
                    <Row>
                        <h3 className={styles.smallTitle}>职位信息</h3>
                        <Form
                            className="form-Wrap"
                            {...formItemLayout}
                            // onSubmit={e => {
                            //     e.preventDefault();
                            //     this.handleSubmit({ newUser });
                            // }}
                        >
                            <Form.Item label="职位名称：">
                                {getFieldDecorator('postCnName', {
                                    initialValue: postCnName,
                                    rules: [
                                        {
                                            required: true,
                                            min: 2,
                                            max: 50,
                                            message: '请输入职位名称'
                                        }
                                    ]
                                })(<Input placeholder="请输入职位名称" />)}
                            </Form.Item>
                            <Form.Item label="职位类型：">
                                {getFieldDecorator('postCnType', {
                                    initialValue: postCnType || undefined,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择职位类型'
                                        }
                                    ]
                                })(
                                    <SelectForm
                                        params={{}}
                                        requireParam={[]}
                                        getData={params =>
                                            getTypeList(params).then(res => {
                                                if (res && res.code === 10000 && res.data) {
                                                    return res.data || [];
                                                }
                                                return [];
                                            })
                                        }
                                        fieldsName={{
                                            selectValue: 'value',
                                            selectTitle: 'name'
                                        }}
                                        // onChange={this.companyChange}
                                        selectProps={{
                                            placeholder: '请选择职位类型'
                                        }}
                                    />
                                )}
                            </Form.Item>
                            <Form.Item label="发布时间：">
                                {getFieldDecorator('releaseTime', {
                                    initialValue: moment(releaseTime),
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择发布时间'
                                        }
                                    ]
                                })(<DatePicker format="YYYY-MM-DD HH:mm" disabled="false" />)}
                            </Form.Item>

                            <Form.Item label="工作地点：">
                                {getFieldDecorator('workPlace', {
                                    initialValue:
                                        // eslint-disable-next-line no-nested-ternary
                                        workPlace !== undefined ? workPlace : userPlace,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择工作地点'
                                        }
                                    ]
                                })(
                                    <Radio.Group>
                                        <Radio value={0}>厦门</Radio>
                                        <Radio value={1}>新加坡</Radio>
                                    </Radio.Group>
                                )}
                            </Form.Item>

                            <Form.Item label="工作性质：">
                                {getFieldDecorator('workNature', {
                                    initialValue: workNature !== undefined ? workNature : 0,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择工作性质'
                                        }
                                    ]
                                })(
                                    <Radio.Group>
                                        <Radio value={0}>全职</Radio>
                                        <Radio value={1}>兼职</Radio>
                                        <Radio value={2}>实习</Radio>
                                    </Radio.Group>
                                )}
                            </Form.Item>
                            <Form.Item label="职位职责：" help="20-1000个字符" style={{ marginBottom: 24 }}>
                                {getFieldDecorator('postCnResponsibilit', {
                                    initialValue: postCnResponsibilit,
                                    rules: [
                                        {
                                            required: true,
                                            min: 20,
                                            max: 1000,
                                            message: '请描述职位的工作内容'
                                        }
                                    ]
                                })(<TextArea placeholder="请描述职位的工作内容" rows={4} />)}
                            </Form.Item>
                            <Form.Item label="任职要求：" help="20-1000个字符">
                                {getFieldDecorator('jobCnRequirements', {
                                    initialValue: jobCnRequirements,
                                    rules: [
                                        {
                                            required: true,
                                            min: 20,
                                            max: 1000,
                                            message: '请描述任职要求（专业技能）'
                                        }
                                    ]
                                })(<TextArea placeholder="请描述任职要求（专业技能）" rows={4} />)}
                            </Form.Item>
                            <Divider />

                            <h3 className={styles.smallTitle}>职位设置</h3>
                            <Form.Item label="是否隐藏职位：">
                                <div>
                                    {getFieldDecorator('hidden', {
                                        initialValue: hidden !== undefined ? hidden : 1,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择是否隐藏职位'
                                            }
                                        ]
                                    })(
                                        <Radio.Group>
                                            <Radio value={0}>是</Radio>
                                            <Radio value={1}>否</Radio>
                                        </Radio.Group>
                                    )}
                                    <div style={{ marginTop: '-10px' }}>隐藏后，此职位不在官网职位列表中显示</div>
                                </div>
                            </Form.Item>
                            <Form.Item label=" " className={styles.nullFormItem}>
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    onClick={e => {
                                        e.preventDefault();
                                        this.handleSubmit({ newUser });
                                    }}
                                >
                                    提交
                                </Button>
                                <Button
                                    style={{ marginLeft: 15 }}
                                    className={styles.btnMr}
                                    onClick={() => {
                                        history.push('/office/info/webSite/recruitList');
                                    }}
                                >
                                    取消
                                </Button>
                            </Form.Item>
                        </Form>
                    </Row>
                </Card>
                <Modal
                    title={modalDelete ? '删除职位' : '取消新增'}
                    visible={visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                >
                    <p>
                        {modalDelete
                            ? '确定要删除这项职位？删除后此职位信息消失，不可恢复！'
                            : '职位信息已变更，是否确定提交？'}
                    </p>
                </Modal>
            </PageHeaderWrapper>
        );
    }
}
export default withRoutePage(
    connect(({ loading, recruitManage }) => ({
        recruitManage,
        loading: loading.models.recruitManage
    }))(Form.create()(RecruitEdit))
);
